<template>
  <div class="roles">
     <!-- 面包屑 -->
     <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 添加按钮 -->
<el-button @click="open" class="addBtn" type="success" plain>添加角色</el-button>
 <!-- 表格数据 -->

    <el-table :data="rolesList">
      <el-table-column  type="expand" >
        <!-- 树形结构 -->
        <template v-slot:default="{ row }">
           <p v-if="row.children.length === 0">暂无权限</p>

         <el-row class="l1" v-for="l1 in row.children" :key="l1.id">
           <el-col :span="4">
             <el-tag @close="delRight(row,l1.id)" closable>{{l1.authName}}</el-tag>
             <i class="el-icon-arrow-right"></i>
           </el-col>
           <el-col :span="20">
             <el-row class="l2" v-for="l2 in l1.children" :key="l2.id">
               <el-col :span="4">
                 <el-tag @close="delRight(row,l2.id)" closable type="success">{{l2.authName}}</el-tag>
                 <i class="el-icon-arrow-right"></i>
               </el-col>
               <el-col :span="20">
                 <el-tag @close="delRight(row,l3.id)" closable type="warning" class="l3" v-for="l3 in l2.children" :key="l3.id">{{l3.authName}}</el-tag>
               </el-col>
             </el-row>
           </el-col>
         </el-row>

        </template>

      </el-table-column>
      <el-table-column  type="index" label="#"></el-table-column>
      <el-table-column prop='roleName' label="角色名称"></el-table-column>
      <el-table-column prop="roleDesc" label="描述"></el-table-column>
      <el-table-column  label="操作">

        <!-- 匿名插槽 -->
        <template v-slot:default={row}>
      <el-button  @click="showAlter(row)" size="mini" type="primary" plain icon="el-icon-edit"></el-button>
      <el-button  @click="delroles(row.id)" size="mini" type="danger" plain icon="el-icon-delete"></el-button>
      <el-button  @click="showAssignDialog(row)" size="mini" type="success" plain icon="el-icon-check">分配权限</el-button>
        </template>

      </el-table-column>

    </el-table>

  <!-- 添加角色对话框 -->
  <el-dialog
    title="添加角色"
    :visible.sync="rolesVisible"
    width="40%">

     <!-- 内容部分 -->
    <el-form ref="form" :model="form" :rules='rules'  label-width="80px">
        <el-form-item label="角色名称"  prop='roleName'>
          <el-input v-model="form.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
         <el-form-item label="角色描述"  prop='roleDesc'>
          <el-input v-model="form.roleDesc" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>

    <template v-slot:footer>
    <el-button @click="rolesVisible = false">取 消</el-button>
    <el-button @click= "addRoles" type="primary">确 定</el-button>
    </template>
</el-dialog>

  <!-- 修改角色对话框 -->
  <el-dialog
    title="修改角色"
    :visible.sync="alterVisible"
    width="40%">

     <!-- 内容部分 -->
    <el-form ref="alterform" :model="alterform" :rules='rules1'  label-width="80px">
        <el-form-item label="角色名称"  prop='roleName'>
          <el-input v-model="alterform.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
         <el-form-item label="角色描述"  prop='roleDesc'>
          <el-input v-model="alterform.roleDesc" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>

    <template v-slot:footer>
    <el-button @click="alterVisible = false">取 消</el-button>
    <el-button @click="alterRoles" type="primary">确 定</el-button>
    </template>
</el-dialog>

<!-- 分配的对话框 -->
<el-dialog
  title="分配权限"
  :visible.sync="assignVisible"
  width="40%">

   <el-tree
        ref="tree"
        node-key="id"
        show-checkbox
        default-expand-all
        :data="data"
        :props="defaultProps">
  </el-tree>

      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="assignVisible = false">取 消</el-button>
          <el-button @click="assignRights" type="primary">分 配</el-button>
        </span>
      </template>
</el-dialog>

  </div>

</template>

<script>
export default {
  methods: {
    open () {
      this.rolesVisible = true
    },
    showAlter (row) {
      this.alterVisible = true
      this.alterform.id = row.id
      this.alterform.roleName = row.roleName
      this.alterform.roleDesc = row.roleDesc
    },
    // 刷新页面
    async  getRoleList () {
      const { data, meta } = await this.$axios.get('roles')
      if (meta.status === 200) {
        this.rolesList = data
      } else {
        this.$message.error(meta.msg)
      }
    },
    async addRoles () {
      try {
        // 1:先校验
        await this.$refs.form.validate()
        // 2：发ajax
        const { meta, data } = await this.$axios.post('roles', this.form)
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          this.rolesVisible = false
          this.getRoleList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    async delroles (id) {
      try {
        await this.$confirm('您确认要删除吗？', '温馨提示', {
          type: 'warning'
        })
        const { meta } = await this.$axios.delete(`roles/${id}`)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          if (this.rolesList.length === 1 && this.pagenum > 1) {
            this.pagenum--
          }
          // 重新渲染
          this.getRoleList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 修改功能
    async alterRoles () {
      try {
        await this.$refs.alterform.validate()
        const { data, meta } = await this.$axios.put(`roles/${this.alterform.id}`, {
          roleName: this.alterform.roleName,
          roleDesc: this.alterform.roleDesc
        })
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          this.alterVisible = false
          this.getRoleList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 删除树状图功能
    async delRight (row, rightID) {
      const { meta, data } = await this.$axios.delete(`roles/${row.id}/rights/${rightID}`)
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        row.children = data
      } else {
        this.$message.error(meta.msg)
      }
    },
    async showAssignDialog (row) {
      this.roleID = row.id
      this.assignVisible = true
      const { meta, data } = await this.$axios.get(`rights/tree`)
      if (meta.status === 200) {
        this.data = data
        const ids = []

        row.children.forEach(l1 => {
          l1.children.forEach(l2 => {
            l2.children.forEach(l3 => {
              ids.push(l3.id)
            })
          })
        })

        this.$refs.tree.setCheckedKeys(ids)
      } else {
        this.$message.error(meta.msg)
      }
    },
    async assignRights () {
      const ids = this.$refs.tree.getCheckedKeys() // 获取全选的
      const halfs = this.$refs.tree.getHalfCheckedKeys() // 获取半选的
      const rids = [...ids, ...halfs].join(',') // 全选和半选的

      const { meta } = await this.$axios.post(`roles/${this.roleID}/rights`, { rids })

      if (meta.status === 200) {
        this.$message.success(meta.msg)
        // 关闭对话框
        this.assignVisible = false
        // 重新渲染
        this.getRoleList()
      } else {
        this.$message.error(meta.msg)
      }
    }
  },
  data () {
    return {
      roleID: '',
      rolesList: [], // 列表
      rolesVisible: false,
      alterVisible: false,
      assignVisible: false,
      pagenum: 1, // 当前页
      data: [],
      defaultProps: {
        children: 'children', // 配置展开的子集
        label: 'authName' // 配置展开的文字
      },
      form: {
        roleName: '',
        roleDesc: ''
      },
      alterform: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }

        ],
        roleDesc: [
          { required: true, message: '角色描述不能为空', trigger: ['blur', 'change'] }

        ]
      },
      rules1: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }

        ],
        roleDesc: [
          { required: true, message: '角色描述不能为空', trigger: ['blur', 'change'] }

        ]
      }
    }
  },
  created () {
    this.getRoleList()
  }
}
</script>

<style lang='less' scopet>
.roles{
  .el-breadcrumb{
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid #ccc
  }
  .addBtn{
    margin: 10px 0;

  }
  .l1 {
  margin-bottom: 10px;
  border-bottom: 1px dotted #ccc;
}
.l2 {
  margin-bottom: 10px;
}
.l3 {
  margin-right: 5px;
  margin-bottom: 5px;
}
}

</style>
